package com.qyhl.webtv.module_news.news.union.town2;

import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.UnionBean;
import com.qyhl.webtv.commonlib.utils.vertical.QTabView;
import com.qyhl.webtv.commonlib.utils.vertical.TabAdapter;
import com.qyhl.webtv.commonlib.utils.vertical.TabView;
import com.qyhl.webtv.commonlib.utils.vertical.VerticalTabLayout;
import com.qyhl.webtv.commonlib.utils.vertical.VerticalViewPager;
import com.weavey.loading.lib.LoadingLayout;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by qyhl on 2018/2/26.
 * 新版乡镇列表
 */

@Route(path = ARouterPathConstant.UNION_TOWN2)
public class Town2ListActivity extends BaseActivity implements Town2ListContract.Town2ListView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.tablayout)
    VerticalTabLayout tablayout;
    @BindView(R2.id.verticalviewpager)
    VerticalViewPager verticalViewPager;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.back_btn)
    ImageView backBtn;

    @Autowired(name = "id")
    String sectionId;
    private Town2ListPresenter mPresenter;

    private Town2ListPagerAdapter mPagerAdapter;

    private List<UnionBean> mDataList;

    private List<String> titleList;

    private List<Fragment> fragmentList;

    @Autowired(name = "title")
    String name;

    private static final float MIN_SCALE = 0.75f;
    private static final float MIN_ALPHA = 0.75f;


    @Override
    protected int getContentView() {
        return R.layout.news_activity_union_town2;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new Town2ListPresenter(this);
        loadMask.setStatus(LoadingLayout.Loading);

        mDataList = new ArrayList<>();

        titleList = new ArrayList<>();

        fragmentList = new ArrayList<>();

        title.setText(name);

        mPresenter.getData(sectionId);
    }

    @Override
    protected void setListener() {
        //重载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getData(sectionId);
        });

        tablayout.addOnTabSelectedListener(new VerticalTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabView tab, int position) {
                verticalViewPager.setCurrentItem(position);
                for (int i = 0; i < titleList.size(); i++) {
                    if (i == position) {
                        tab.setBackgroundColor(ContextCompat.getColor(Town2ListActivity.this, R.color.white));
                    } else {
                        tablayout.getTabAt(i).setBackgroundColor(ContextCompat.getColor(Town2ListActivity.this, R.color.global_background));
                    }
                }

            }

            @Override
            public void onTabReselected(TabView tab, int position) {

            }
        });

        verticalViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tablayout.setTabSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        backBtn.setOnClickListener(v -> finish());
    }


    @Override
    public void setData(List<UnionBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mDataList = beanList;
        fragmentList.clear();

        Map<UnionBean, List<UnionBean>> listMap = group(mDataList);
        if (listMap == null) {
            setError("解析异常，加载失败！");
            return;
        } else {
            for (Map.Entry<UnionBean, List<UnionBean>> vo : listMap.entrySet()) {
                titleList.add(vo.getKey().getName());
                fragmentList.add(Town2ListFragment.newInstance(vo.getValue()));
            }
        }

        tablayout.setTabAdapter(new MyTabAdapter(titleList));
        try {
            tablayout.getTabAt(0).setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        } catch (Exception e) {
        }
        mPagerAdapter = new Town2ListPagerAdapter(getSupportFragmentManager(), fragmentList);
        mPagerAdapter.setData(titleList);
        verticalViewPager.setAdapter(mPagerAdapter);
        verticalViewPager.setPageMargin(getResources().
                getDimensionPixelSize(R.dimen.news_pagemargin));
        verticalViewPager.setPageMarginDrawable(new ColorDrawable(
                ContextCompat.getColor(this, R.color.white)));


        verticalViewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View view, float position) {
                int pageWidth = view.getWidth();
                int pageHeight = view.getHeight();

                if (position < -1) { // [-Infinity,-1)
                    // This page is way off-screen to the left.
                    view.setAlpha(0);

                } else if (position <= 1) { // [-1,1]
                    // Modify the default slide transition to shrink the page as well
                    float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                    float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                    float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                    if (position < 0) {
                        view.setTranslationY(vertMargin - horzMargin / 2);
                    } else {
                        view.setTranslationY(-vertMargin + horzMargin / 2);
                    }

                    // Scale the page down (between MIN_SCALE and 1)
                    view.setScaleX(scaleFactor);
                    view.setScaleY(scaleFactor);

                    // Fade the page relative to its size.
                    view.setAlpha(MIN_ALPHA +
                            (scaleFactor - MIN_SCALE) /
                                    (1 - MIN_SCALE) * (1 - MIN_ALPHA));

                } else { // (1,+Infinity]
                    // This page is way off-screen to the right.
                    view.setAlpha(0);
                }
            }
        });


    }

    /**
     * 分组
     *
     * @param unionBeanList
     * @return
     */
    private Map<UnionBean, List<UnionBean>> group(List<UnionBean> unionBeanList) {
        Map<UnionBean, List<UnionBean>> resultMap = new LinkedHashMap<>();
        try {
            for (int i = 0; i < unionBeanList.size(); i++) {
                if (unionBeanList.get(i).getParentid().equals(sectionId)) {
                    List<UnionBean> tmpList = new ArrayList<>();
                    for (int j = 0; j < unionBeanList.size(); j++) {
                        if (unionBeanList.get(j).getParentid().equals(unionBeanList.get(i).getId())) {
                            tmpList.add(unionBeanList.get(j));
                        }
                    }
                    resultMap.put(unionBeanList.get(i), tmpList);
                }
            }
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void setError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setErrorText(msg);
    }

    @Override
    public void setEmpty(String msg) {
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setEmptyText(msg);
    }

    @Override
    public void setNetError(String msg) {
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setNoNetworkText(msg);
    }

    class MyTabAdapter implements TabAdapter {

        List<String> titles;

        public MyTabAdapter(List<String> titles) {
            this.titles = titles;
        }

        public void setTitles(List<String> titles) {
            this.titles = titles;
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public int getBadge(int position) {
            return 0;
        }

        @Override
        public QTabView.TabIcon getIcon(int position) {
            return null;
        }

        @Override
        public QTabView.TabTitle getTitle(int position) {
            return new QTabView.TabTitle.Builder(Town2ListActivity.this)
                    .setContent(titles.get(position))
                    .setTextColor(getResources().getColor(R.color.global_base), getResources().getColor(R.color.global_black_lv1))
                    .build();
        }

        @Override
        public int getBackground(int position) {
            return 0;
        }
    }
}
